package cn.itcast.web.controller.system;

import cn.hutool.core.util.StrUtil;
import cn.itcast.domain.system.Module;
import cn.itcast.service.system.ModuleService;
import cn.itcast.web.controller.BaseController;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping(value = "/system/module", name = "模块管理")
public class ModuleController extends BaseController {

    @Autowired
    private ModuleService moduleService;

    @RequestMapping(value = "/list", name = "查询模块")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        PageInfo page = moduleService.findByPage(pageNum, pageSize);
        request.setAttribute("page", page);
        return "system/module/module-list";
    }

    @RequestMapping(value = "/toAdd", name = "新增页面")
    public String toAdd() {
        // 查询所有模块
        List<Module> menus = moduleService.findAll();
        request.setAttribute("menus", menus);

        return "system/module/module-add";
    }

    @RequestMapping(value = "/edit", name = "新增/修改")
    public String edit(Module module) {
        // 顶级模块的插入，因为数据库表有外键约束，不能添加"" 需要设置为null
        if (StrUtil.hasEmpty(module.getParentId())) {
            module.setParentId(null);
            module.setParentName(null);
        }
        // 判断是否携带id
        if (StrUtil.hasEmpty(module.getId())) {

            moduleService.save(module);
        }else{
            moduleService.update(module);
        }

        return "redirect:/system/module/list.do";
    }

    @RequestMapping(value = "/toUpdate", name = "修改页面")
    public String toUpdate(String id) {
        // 查询所有模块
        List<Module> menus = moduleService.findAll();
        request.setAttribute("menus", menus);

        // 根据id查询模块
        Module module = moduleService.findById(id);
        request.setAttribute("module", module);
        return "system/module/module-update";
    }

    @RequestMapping(value = "/delete",name = "删除")
    public String delete(String id){
        moduleService.delete(id);
        return "redirect:/system/module/list.do";
    }
}
